package com.gjintel.sdk.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import org.junit.Test;

import com.gjintel.business.proj.model.ProjectInfo;
import com.gjintel.workflow.WorkflowUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class WordHandler {
	private Configuration configuration = null;
	
	//Log logger = LogFactory.getLog(WordHandler.class);
	public WordHandler() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("UTF-8");
	}

	private Template getTemplate(String templatePath, String templateName) throws IOException {
		configuration.setClassForTemplateLoading(this.getClass(), templatePath);
		Template t = null;
		t = configuration.getTemplate(templateName);
		t.setEncoding("UTF-8");
		return t;
	}
	
	
	public void write(String templatePath, String templateName, Map dataMap, Writer out) throws WordHandlerException {
		try {
			Template t = getTemplate(templatePath, templateName);
			t.process(dataMap, out);
		} catch (IOException e) {
			// logger.error(e);
			throw new WordHandlerException(e);
		} catch (TemplateException e) {
			// logger.error(e);
			throw new WordHandlerException(e);
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				// logger.error(e);
				throw new WordHandlerException(e);
			}
		}
	}
	
//	@Test
	public void test2() throws IOException{
		//准备测试数据
		List<String> tenders = new ArrayList<String>(){
			{
				add("张1");add("张2");add("张3");add("张4");add("张5");add("张6");add("张7");add("张8");add("张9");add("张10");
			}
		};
		
		int i=0;
		StringBuilder sb= new StringBuilder();
		//加入html头
		sb.append(this.fileToString(new File("").getAbsolutePath()+"/htmlHeader.html"));
		Map<String,String> m2= new HashMap<String,String>();
		String tempModel="";
		String path="E:\\h3.html";
		for(String tenderName:tenders){
			i++;
			if(i %4!=0){
				int j= i%4 ;
			    m2.put("tender"+ j, tenderName);
			}else{
				m2.put("tender4", tenderName);
				if(i<=4)
					tempModel= "model1.html";
				else
					tempModel="model2.html";
						
				generateWord(path, m2,tempModel);
				m2.clear();
				sb.append(this.fileToString(path));
			}
		}
		
		//如果list不是4的整数，则现加入尾部数据
		if(i%4!=0 && i>0){
			int j = i%4;
			for(;4-j>0;){
				j++;
				m2.put("tender"+ j, "");
			}
			generateWord(path, m2,tempModel);
			sb.append(this.fileToString(path));
		}
		sb.append("</body></html>");
		System.out.println(sb.toString());
		this.string2File(sb.toString(), "e:\\h6.html");
	}	

	
	//把文件内容转换为String 类型
	public String fileToString(String fileName) throws IOException{
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(fileName));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		String line="";
		StringBuffer buffer = new StringBuffer();
		while((line=br.readLine())!=null){
			buffer.append(line);
		}
		String fileContent = buffer.toString();
		return fileContent;
	}
	
//	@Test
	public void test1(){
		ProjectInfo info=new ProjectInfo();
		info.setName("包河区政府项目");
		info.setId("88888888");
		String path="E:\\测试.doc";
		Map map = new HashMap();
		//map.put("projectName","农村电ss商项目");
		map.put("project",info);
		
		generateWord(path, map,"test.xml");
		
		
	}
	
	  /**
     * 将字符串写入指定文件(当指定的父路径中文件夹不存在时，会最大限度去创建，以保证保存成功！)
     *
     * @param res            原字符串
     * @param filePath 文件路径
     * @return 成功标记
     */
    public static boolean string2File(String res, String filePath) {
            boolean flag = true;
            BufferedReader bufferedReader = null;
            BufferedWriter bufferedWriter = null;
            try {
                    File distFile = new File(filePath);
                    if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs();
                    bufferedReader = new BufferedReader(new StringReader(res));
                    bufferedWriter = new BufferedWriter(new FileWriter(distFile));
                    char buf[] = new char[1024];         //字符缓冲区
                    int len;
                    while ((len = bufferedReader.read(buf)) != -1) {
                            bufferedWriter.write(buf, 0, len);
                    }
                    bufferedWriter.flush();
                    bufferedReader.close();
                    bufferedWriter.close();
            } catch (IOException e) {
                    e.printStackTrace();
                    flag = false;
                    return flag;
            } finally {
                    if (bufferedReader != null) {
                            try {
                                    bufferedReader.close();
                            } catch (IOException e) {
                                    e.printStackTrace();
                            }
                    }
            }
            return flag;
    }
	
	

	/**
	 * @description 生成world 
	 * @author wwang 
	 * @date 2016-8-26
	 * @param path world保存路径
	 * @param map 参数
	 * @param worldXmlPath world 文档模板路径
	 */
	public void generateWord(String path, Map map,String worldXmlPath) {
		WorkflowUtils wfu= new WorkflowUtils();
		System.out.print("world文档生成成功!......");
		
        WordHandler handler = new WordHandler();
        Writer out;
		try {
			out = new OutputStreamWriter(new FileOutputStream(path), "UTF-8");
			handler.write("", worldXmlPath, map, out);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (WordHandlerException e) {
			e.printStackTrace();
		}
	}
	
	
	public static void main(String[] args) throws WordHandlerException{
		
		WorkflowUtils wfu= new WorkflowUtils();
		System.out.print(wfu.toString());
//		Map map = new HashMap();
//		          map.put("user","包河区政府");
//		          map.put("projectName","农村电商项目");
//		          WordHandler handler = new WordHandler();
//		          Writer out;
//				try {
//					out = new OutputStreamWriter(new FileOutputStream("E:\\测试.doc"), "UTF-8");
//					
//					 handler.write("/resources", "test.xml", map, out);
//				} catch (UnsupportedEncodingException e) {
//					e.printStackTrace();
//				} catch (FileNotFoundException e) {
//					e.printStackTrace();
//				}
		 // WordHandler handler= new WordHandler();
		         

	}
	
}
